package com.baichang.taoshunda.utils;

import cn.jpush.api.push.PushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import com.baichang.framework.utils.ConfigurationHandle;
import com.baichang.framework.utils.JPushHelper;

import java.util.List;

public class DeliveryJPushHelper extends JPushHelper {

    private String secret;
    private String key;
    private boolean isDev;

    private String configName = "distribution.properties";

    public DeliveryJPushHelper() {
        init();
    }

    public DeliveryJPushHelper(String configName) {
        this.configName = configName;
        init();
    }

    private void init() {
        ConfigurationHandle configurationHandle = new ConfigurationHandle(configName);
        secret = configurationHandle.getStringValue("secret");
        key = configurationHandle.getStringValue("key");
        isDev = configurationHandle.getStringValue("isApns").equals("1");
    }

    public boolean sendMsgByAlias(Message message, List<String> alias) {
        PushClient _client = new PushClient(secret, key);
        PushPayload payload = PushPayload.newBuilder().setPlatform(Platform.android_ios()).setAudience(Audience.alias(alias)).setOptions(
                Options.newBuilder().setApnsProduction(isDev).build())
                .setMessage(message)
                .build();
        return push(_client, payload);
    }

    private boolean push(PushClient client, PushPayload payload) {
        try {
            PushResult result = client.sendPush(payload);
            if (result.isResultOK()) {
                if (result.sendno != 0) {
                    return true;
                }
            }
        } catch (Exception e) {
            return false;
        }
        return false;
    }

}
